package middleware

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/jwts"
	redisjwts "KumquatDrivesServices/service/redis_jwts"

	"github.com/gin-gonic/gin"
)

const (
	SetKey = "user_id"
)

func AuthMiddleware(c *gin.Context) {
	//获取Toekn
	token := c.GetHeader("Authorization")
	if token == "" {
		res.FailWithCode(res.INVALID_TOKEN, c)
		c.Abort()
		return
	}
	ParseAccessToken, err := jwts.ParseAccessToken(token)
	if err != nil {
		switch err {
		case jwts.ErrTokenExpired:
			res.FailWithCode(res.EXPIRED_TOKEN, c)
		default:
			res.FailWithCode(res.INVALID_TOKEN, c)
		}
		c.Abort()
		return
	}
	bol, HasTokenBlackErr := redisjwts.HasTokenBlack(token)
	if HasTokenBlackErr != nil {
		res.FailWithCode(res.SYS_ERR, c)
		c.Abort()
		return
	}
	if !bol {
		res.FailWithCode(res.INVALID_TOKEN, c)
		c.Abort()
		return
	}
	c.Set(SetKey, ParseAccessToken.UserId)
}
